package com.imageFilters.view;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.imageFilters.GaussianBlurFilter;
import com.imageFilters.ImageData;
import com.imageFilters.ImageFilterInterface;
import com.imageFilters.InvertFilter;
import com.imageFilters.LomoFilter;
import com.imageFilters.OldPhotoFilter;
import com.vikaa.wowo.widget.MyAdapterView;
import com.vikaa.wowo.widget.MyGallery;
import com.vikaa.wowo.widget.MyAdapterView.OnItemClickListener;

import vikaa.framework.AppContext;
import vikaa.tools.DialogService;
import vikaa.tools.FileUtils;
import vikaa.tools.ImageUtils;
import vikaa.tools.Logger;
import vikaa.tools.StringUtils;
import vikaa.wowo.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class PictureFilter extends Activity  {
	GalleryAdapter m_galleryadapter;
    private static final int FINISH_GET_APPS = 1024;
    ArrayList<Filter_item> m_filter;
    PackageManager m_packageMgr;
    MyGallery g2;
	
	private ImageView imageView;
	private Bitmap bitmap;
	//模糊
	
	private ImageView btnYes;
	private ImageView btnNo;
	private int type;
	private String theLarge;
	private String desPath;
	private String prefix;
	
	Matrix matrix = new Matrix(); 
	Matrix savedMatrix = new Matrix(); 

	static final int NONE = 0; 
	static final int DRAG = 1; 
	static final int ZOOM = 2; 
	int mode = NONE; 

	PointF start = new PointF(); 
	PointF mid = new PointF(); 
	float oldDist = 1f; 
     
     
	private final static String CAMERA_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.picture_filter);
		imageView= (ImageView) findViewById(R.id.imgfilter);
		//imageView.setOnTouchListener(new MulitPointTouchListener ());
		String path = getIntent().getExtras().getString("path");
		type = getIntent().getExtras().getInt("type");
		if(FileUtils.checkSDCard()){
			Logger.i(path);
		}
		File file = null;
		try{
			file = new File(path);
		}catch(Exception e){
			finish();
		}
		prefix = "_" + file.getName();
		if(type != 3 ){
			bitmap= ImageUtils.getBitmapByPath(path, (new AppContext().getDisplayWidth(PictureFilter.this)));
			try {
				ImageUtils.saveImageToSD(Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/原图" + prefix, bitmap, 100);
				desPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/原图" + prefix;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			bitmap= ImageUtils.getBitmapByPath(path, (new AppContext().getDisplayHeighth(PictureFilter.this)));
		}	
		
		if(type == 3){
			File file1 = new File(path);
			String name = file1.getName();
			name = "原图"+ name.substring(name.indexOf("_"),name.length());
			prefix = name.substring(name.indexOf("_"),name.length());
			path = CAMERA_DIR + name;
			Log.i("sf", path);
			bitmap= ImageUtils.getBitmapByPath(path, (new AppContext().getDisplayHeighth(PictureFilter.this)));
		}
		imageView.setImageBitmap(bitmap);
		initMyGallery();
		
		btnYes = (ImageView) findViewById(R.id.btn_yes);
		btnYes.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent();
				Bundle b = new Bundle();
				b.putString("despath", desPath);
				i.putExtras(b);
				setResult(RESULT_OK, i);
				finish();
			}
		});
		
		btnNo = (ImageView) findViewById(R.id.btn_no);
		btnNo.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				bitmap = null;
				if(type == 1){//退回相册
					Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
					intent.addCategory(Intent.CATEGORY_OPENABLE); 
					intent.setType("image/*"); 
					startActivityForResult(Intent.createChooser(intent, "选择图片"),ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD); 
				}
				if(type == 2){
					String savePath = "";
					//判断是否挂载了SD卡
					String storageState = Environment.getExternalStorageState();		
					if(storageState.equals(Environment.MEDIA_MOUNTED)){
						savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/";//存放照片的文件夹
						File savedir = new File(savePath);
						if (!savedir.exists()) {
							savedir.mkdirs();
						}
					}
					
					//没有挂载SD卡，无法保存文件
					if(StringUtils.isEmpty(savePath)){
						Toast.makeText(getApplicationContext(), getString(R.string.msg_save_image_fail),Toast.LENGTH_SHORT).show();
						return;
					}

					String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
					String fileName = "vikaa_" + timeStamp + ".jpg";//照片命名
					File out = new File(savePath, fileName);
					Uri uri = Uri.fromFile(out);
					
					theLarge = savePath + fileName;//该照片的绝对路径
					
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
					startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
				}
				if(type == 3){
					finish();
				}
			}
		});
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Intent i = new Intent();
		Bundle b = new Bundle();
		b.putString("despath", desPath);
		i.putExtras(b);
		setResult(RESULT_OK, i);
	}
	@Override
	protected void onActivityResult(final int requestCode, int resultCode, final Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode != RESULT_OK) return;
		final Handler handler = new Handler(){
			public void handleMessage(Message msg) {
				if(msg.what == 1 && msg.obj != null){
					//显示图片
					bitmap = (Bitmap)msg.obj;
					imageView.setImageBitmap(bitmap);
					initFilter();
					g2.setSelection(0);
				}
			}
		};
		
		new Thread(){
			public void run() 
			{
				Bitmap bmap = null;
				
		        if(requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD) 
		        {         	
		        	if(data == null)  return;
		        	
		        	Uri thisUri = data.getData();
		        	String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(thisUri);
		        	
		        	//如果是标准Uri
		        	if(StringUtils.isEmpty(thePath))
		        	{
		        		theLarge = ImageUtils.getAbsoluteImagePath(PictureFilter.this,thisUri);
		        	}
		        	else
		        	{
		        		theLarge = thePath;
		        	}
		        	
		        	if(bmap == null && !StringUtils.isEmpty(theLarge))
		        	{
		        		bmap= ImageUtils.getBitmapByPath(theLarge, (new AppContext().getDisplayWidth(PictureFilter.this))/2);
		        	}
		        }
		        //拍摄图片
		        else if(requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA)
		        {	
		        	if(bmap == null && !StringUtils.isEmpty(theLarge))
		        	{
		        		bmap= ImageUtils.getBitmapByPath(theLarge, (new AppContext().getDisplayWidth(PictureFilter.this))/2);
		        	}
		        }
		        
				if(bmap!=null)
				{
					File file = new File(theLarge);
					prefix = "_" + file.getName();
					try {
						ImageUtils.saveImageToSD(Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/原图" + prefix, bmap, 100);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					desPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/原图" + prefix;
					
					Message msg = new Message();
					msg.what = 1;
					msg.obj = bmap;
					handler.sendMessage(msg);
				}				
			};
		}.start();
	}
	
	private void initMyGallery() {
		initFilter();
        m_galleryadapter = new GalleryAdapter(this, m_filter, m_packageMgr);
        g2 = (MyGallery) findViewById(R.id.myGallery);
        g2.setVisibility(View.INVISIBLE);
        g2.setAdapter(m_galleryadapter);
        g2.setSelection(0);
        g2.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(MyAdapterView<?> parent, View view,
					int position, long id) {
				if(!m_filter.get(position).isSelected() ){
					m_filter.get(position).setSelected(true);
					new processImageTask(m_filter.get(position).getFilter_name(), m_filter.get(position).getFilter()).execute();
					for(int i=0;i<m_filter.size();i++){
						if(i != position){
							m_filter.get(i).setSelected(false);
						}
					}
				}
			}
		});
    }
	private void initFilter(){
		m_filter = new ArrayList<Filter_item>();
		Filter_item ft = new Filter_item();
		ft.setFilter(new LomoFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.icon));
		ft.setFilter_name("原图");
		ft.setSelected(false);
		m_filter.add(ft);
		
		ft = new Filter_item();
		ft.setFilter(new LomoFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.icon));
		ft.setFilter_name("Lomo");
		ft.setSelected(false);
		m_filter.add(ft);
		
		ft = new Filter_item();
		ft.setFilter(new OldPhotoFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.icon));
		ft.setFilter_name("老照片");
		ft.setSelected(false);
		m_filter.add(ft);
		
		ft = new Filter_item();
		ft.setFilter(new InvertFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.icon));
		ft.setFilter_name("底片");
		ft.setSelected(false);
		m_filter.add(ft);
		
		/*ft = new Filter_item();
		ft.setFilter(new GrayFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.ic_launcher));
		ft.setFilter_name("黑白");
		ft.setSelected(false);
		m_filter.add(ft);
		
		ft = new Filter_item();
		ft.setFilter(new FilmFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.ic_launcher));
		ft.setFilter_name("电影");
		ft.setSelected(false);
		m_filter.add(ft);*/
		
	/*	ft = new Filter_item();
		ft.setFilter(new NightVisionFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.ic_launcher));
		ft.setFilter_name("夜间");
		ft.setSelected(false);
		m_filter.add(ft);*/
		
		/*ft = new Filter_item();
		ft.setFilter(new EdgeFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.ic_launcher));
		ft.setFilter_name("素描");
		ft.setSelected(false);
		m_filter.add(ft);*/
		
		/*ft = new Filter_item();
		ft.setFilter(new SepiaFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.ic_launcher));
		ft.setFilter_name("温暖");
		ft.setSelected(false);
		m_filter.add(ft);*/
		
		ft = new Filter_item();
		ft.setFilter(new GaussianBlurFilter());
		ft.setFilter_logo(getResources().getDrawable(R.drawable.icon));
		ft.setFilter_name("模糊");
		ft.setSelected(false);
		m_filter.add(ft);
		
	
	}
	public class processImageTask extends AsyncTask<Void, Void, Bitmap> {
		private ImageFilterInterface filter;
        private String name = null;
		public processImageTask(String name, ImageFilterInterface imageFilter) {
			this.filter = imageFilter;
			this.name = name;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			DialogService.showProgressDialog(PictureFilter.this, "操作中");
		}

		public Bitmap doInBackground(Void... params) {
			ImageData img = null;
			String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vikaa/Camera/";
			String path = savePath + name + prefix;
			desPath = path;
			try	{   
				File file = new File(path);
				
				if(file.exists()){
					Log.i("af", path);
					return ImageUtils.getBitmapByPath(path, (new AppContext().getDisplayWidth(PictureFilter.this)));
				}
				else{
					//img = new ImageData(bitmap);
					img = filter.imageProcess(bitmap);
					//生成文件
					ImageUtils.saveImageToSD(path, img.getimage(), 100);
					return img.getimage();
				}
	    	}
			catch(Exception e){
				if (img != null && img.image.isRecycled() && img.srcBitmap.isRecycled()) {
					img.image.recycle();
					img.image = null;
					img.srcBitmap.recycle();
					img.srcBitmap = null;
					System.gc(); 
				}
				DialogService.closeProgressDialog();
			}
			finally{
				if (img != null && img.image.isRecycled() && img.srcBitmap.isRecycled()) {
					img.image.recycle();
					img.image = null;
					img.srcBitmap.recycle();
					img.srcBitmap = null;
					System.gc(); 
				}
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
			if(result != null){
				super.onPostExecute(result);
				/*if(name.equals("模糊")){
					frontview.setVisibility(View.VISIBLE);
					brbmp = result;
					frontview.setImageBitmap(brbmp);
				}else{*/
					imageView.setImageBitmap(result);	
				//} 
			}
			DialogService.closeProgressDialog();
		}
	}
	
}
